package com.dz.scrm.mvp.ui

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.provider.CallLog
import android.provider.ContactsContract
import android.telephony.TelephonyManager
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.dz.scrm.R
import com.dz.scrm.app.config.*
import com.dz.scrm.app.receiver.CODE_PUSH_DATA
import com.dz.scrm.app.receiver.DZBroadCastReceiver
import com.dz.scrm.app.receiver.PushMsgBean
import com.dz.scrm.constant.CACHE_CHECK_UPDATE
import com.dz.scrm.constant.CACHE_LOGIN_STATE
import com.dz.scrm.constant.INTENT_REQUEST_PERMISSION
import com.dz.scrm.mvp.model.entity.*
import com.dz.scrm.mvp.presenter.DZPresent
import com.dz.scrm.mvp.ui.fragment.MineFragment
import com.dz.scrm.mvp.ui.fragment.PhoneCallFragment
import com.dz.scrm.mvp.ui.fragment.PhoneRecordFragment
import com.dz.scrm.utils.*
import com.dz.scrm.utils.JsonHelper.parserJson2Object
import com.dz.scrm.utils.SharedPreferencesUtil.COMPANY_INFO
import com.dz.scrm.utils.SharedPreferencesUtil.TOKEN
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.lxj.xpopup.XPopup
import com.miui.enterprise.sdk.PhoneManager
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_home.*
import me.jessyan.art.base.AdapterViewPager
import me.jessyan.art.integration.AppManager
import me.jessyan.art.mvp.IView
import me.jessyan.art.mvp.Message
import me.jessyan.art.utils.ArtUtils
import me.jessyan.art.utils.DeviceUtils
import org.litepal.LitePal
import org.litepal.extension.find
import org.simple.eventbus.Subscriber
import org.simple.eventbus.ThreadMode
import java.util.*
import kotlin.collections.ArrayList

/**
 * 作者：fanda
 * 日期：2021/4/23 10:53
 * 描述：主页面
 */
class HomeActivity : DZActivity<DZPresent>(), IView {
    private val mTitles = listOf("通话记录", "拨号", "我")
    private var mFragments = mutableListOf<Fragment>()
    private val mmIconUnselectIds = listOf(
        R.mipmap.icon_phone_record_unselected,
        R.mipmap.icon_phone_call_unselected,
        R.mipmap.icon_mine_unselected
    )
    private val mIconSelectIds = listOf(
        R.mipmap.icon_phone_record_selected,
        R.mipmap.icon_phone_call_selected,
        R.mipmap.icon_mine_selected
    )
    private val mTabEntities = ArrayList<CustomTabEntity>()
    private var receiver: DZBroadCastReceiver? = null
    private var mExitTime: Long = 0
    private lateinit var record: CachePhoneRecord
    private var pushMsgBean: PushMsgBean? = null
    private var phoneRingTime: Long = 0L

    private val columns = arrayOf(
        CallLog.Calls.CACHED_NAME // 通话记录的联系人
        , CallLog.Calls.NUMBER // 通话记录的电话号码
        , CallLog.Calls.DATE // 通话记录的日期
        , CallLog.Calls.DURATION // 通话时长
        , CallLog.Calls.TYPE // 通话类型
        , CallLog.Calls.GEOCODED_LOCATION// 归属地
        , CallLog.Calls.CACHED_NUMBER_TYPE
    ) // }


    override fun initView(savedInstanceState: Bundle?) = R.layout.activity_home

    override fun initData(savedInstanceState: Bundle?) {
        AppManager.getAppManager().killAll(HomeActivity::class.java)
        SharedPreferencesUtil.saveStatus(CACHE_LOGIN_STATE, true)
        mPresenter.requestPermission(Message.obtain(this, CommonMessageEntity()))
        registerReceiver()
        initTabLayout()
        if (isNetworkAvailable()) {
            LoggerUtils.d("上传之前没上传成功的音频文件")
            mPresenter.queryNoUploadFileDatas(Message.obtain(this, false))
        }
        mPresenter.checkVersion(Message.obtain(this))
    }

    /**
     * 通过系统数据库获取通话记录
     */
    private fun getPhoneRecord() {
        contentResolver.query(
            CallLog.Calls.CONTENT_URI,
            columns,
            null,
            null,
            CallLog.Calls.DEFAULT_SORT_ORDER
        )?.apply {
            var i = 0
            while (moveToNext() && i < 1) {
                var name: String? = getString(getColumnIndex(CallLog.Calls.CACHED_NAME))
                var number: String = getString(getColumnIndex(CallLog.Calls.NUMBER))
                val duration: Int = getInt(getColumnIndex(CallLog.Calls.DURATION))
                val type: Int = getInt(getColumnIndex(CallLog.Calls.TYPE))
                val address: String? = getString(getColumnIndex(CallLog.Calls.GEOCODED_LOCATION))

                //如果名字为空，在通讯录查询一次有没有对应联系人
//                if (name == null || name == "") {
//                    var j = 0
//                    contentResolver.query(
//                        ContactsContract.Contacts.CONTENT_URI,
//                        null,
//                        null,
//                        null,
//                        null
//                    )?.apply {
//                        while (moveToNext() && j < 1) {
//                            //获取联系人姓名
//                            name = getString(getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
//                            j++
//                        }
//                        if (Integer.parseInt(Build.VERSION.SDK) < 14) {
//                            //只有4.0以下才需要手动关闭
//                            close()
//                        }
//                    }

                    val companyInfoBean = getInfoBean<CompanyInfoBean>(COMPANY_INFO)
                    //对电话号码做处理
                    if (!StringUtils.isEmpty(number)) {
                        if (isHiddenPhoneNum() || number.length > 11) {
                            number = PhoneManager.getInstance().decodePhoneNumber(number)
                        }
                    }
                    val areaCode = PhoneManager.getInstance().getAreaCode(number)
                    if ("+86" in number) {
                        number = number.replace("+86", "")
                    }

                    LoggerUtils.d(
                        "name:$name -> number:$number -> duration:$duration -> type:$type" +
                                "-> areaCode:$areaCode -> address:$address -> 时间差： ${(record.phoneEndTime - record.phoneStartTime) / 1000}"
                    )
//                    var date = Date(record.phoneRingTime)
//                    val cal = Calendar.getInstance()
//                    cal.time = date
//                    cal.add(Calendar.SECOND, duration)
//                    date = cal.time
                    if (pushMsgBean != null) {
                        name = pushMsgBean!!.customerName
                        pushMsgBean = null
                    }

                    record.apply {
                        userName = name ?: ""
                        relegation = if (address.isNullOrEmpty()) "未知" else address
                        customerPhone = number
                        userPhone = companyInfoBean?.account ?: ""
                        // 通话时长
                        phoneDurationTime = duration
                        save()
                    }

                    // 存储带分组的全部通话表
                    val allGroupRecord = CacheAllPhoneRecord().apply { copy(record) }
                    val cacheAllPhoneRecordList = LitePal.where(
                        "user_id = ? and tenant_id = ?",
                        companyInfoBean?.user_id,
                        companyInfoBean?.tenant_id
                    ).find<CacheAllPhoneRecord>()
                    if (cacheAllPhoneRecordList.isEmpty()) {
                        // 添加一条新数据
                        allGroupRecord.save()
                    } else {
                        val result = cacheAllPhoneRecordList.lastOrNull {

                            val a =
                                !allGroupRecord.isInCall() && (!it.isInCall() || it.inAccept())// 最后一条信息是打出的，新加入的信息是打出的或是打进已接的才满足
                            val b =
                                allGroupRecord.inAccept() && (!it.isInCall() || it.inAccept())  // 最后一条信息是打进已接的，新加入的信息打进已接或只要是打出的才满足
                            val c =
                                allGroupRecord.inWait() && it.inWait()  // 最后一条信息是打进未接的（标红），新加入的信息也是要打进未接才满足
//                            LoggerUtils.d("时间差；${calculateDiffTime(it.phoneStartTime, allGroupRecord.phoneStartTime)}")
                            (calculateDiffTime(
                                it.phoneStartTime,
                                allGroupRecord.phoneStartTime
                            ) < 60 && allGroupRecord.customerPhone == it.customerPhone) && (a || b || c)
                        }
                        if (result == null) {
                            // 添加一条新数据
                            allGroupRecord.save()
                        } else {
                            result.size++
                            result.phoneStatus = allGroupRecord.phoneStatus
                            result.phoneCallType = allGroupRecord.phoneCallType
                            result.phoneStartTime = allGroupRecord.phoneStartTime
                            result.save()
                        }
                    }

                    // 存储带分组的未接通话表
                    if (!record.isConnect() && record.isInCall()) { // 如果是未接来电
                        val waitGroupRecord = CacheWaitPhoneRecord().apply { copy(record) }
                        val cacheWaitPhoneRecordList = LitePal.where(
                            "user_id = ? and tenant_id = ?",
                            companyInfoBean?.user_id,
                            companyInfoBean?.tenant_id
                        ).find<CacheWaitPhoneRecord>()
                        if (cacheWaitPhoneRecordList.isEmpty()) {
                            // 添加一条新数据
                            waitGroupRecord.save()
                        } else {
                            val result = cacheWaitPhoneRecordList.lastOrNull {
                                calculateDiffTime(
                                    it.phoneStartTime,
                                    waitGroupRecord.phoneStartTime
                                ) < 60 && allGroupRecord.customerPhone == it.customerPhone
                            }
                            if (result == null) {
                                // 添加一条新数据
                                waitGroupRecord.save()
                            } else {
                                result.size++
                                result.phoneStartTime = waitGroupRecord.phoneStartTime
                                result.save()
                            }
                        }
                    }

                    i++
//                }
                if (Integer.parseInt(Build.VERSION.SDK) < 14) {
                    //只有4.0以下才需要手动关闭
                    close()
                }
            }
        }
    }

    private fun initTabLayout() {
        for ((index, title) in mTitles.withIndex()) {
            when (index) {
                0 -> mFragments.add(index, PhoneRecordFragment.getInstance())
                1 -> mFragments.add(index, PhoneCallFragment.getInstance())
                2 -> mFragments.add(index, MineFragment.getInstance())
            }
            mTabEntities.add(
                index,
                TabEntity(title, mIconSelectIds[index], mmIconUnselectIds[index])
            )
        }
        view_pager.setNoScroll(true)
        view_pager.offscreenPageLimit = 2
        view_pager.adapter =
            AdapterViewPager(supportFragmentManager, mFragments, mTitles.toTypedArray())
        view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                tab_layout.currentTab = position
            }

        })
        tab_layout.setTabData(mTabEntities)
        tab_layout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                view_pager.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }

        })
    }

    /***
     * 动态注册广播
     */
    private fun registerReceiver() {
        receiver = DZBroadCastReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(BROADCAST_INCOMING_CALL) //接收到来电广播
        intentFilter.addAction(BROADCAST_OUTGOING_CALL) //接收到去电广播
        intentFilter.addAction(BROADCAST_CALL_CONNECTED) //电话接通广播
        intentFilter.addAction(BROADCAST_CALL_DISCONNECTED) //电话挂断广播
        intentFilter.addAction(BROADCAST_CALL_REJECT) //来电话拒接广播
//        intentFilter.addAction("ACTION_CALL_RECORD");//通话录音完成广播
        intentFilter.addAction(BROADCAST_CALL_RECORD) //通话录音文件
        intentFilter.addAction(BROADCAST_ACTION_SIM_LOADED) //通话录音文件
        intentFilter.addAction(BROADCAST_ACTION_SIM_ABSENT) //通话录音文件
        registerReceiver(receiver, intentFilter)
    }

    override fun obtainPresenter() =
        DZPresent(ArtUtils.obtainAppComponentFromContext(this), RxPermissions(this))

    override fun handleMessage(message: Message) {
        when (message.what) {
            WHAT_CHECK_VERSION -> {
                val checkVersionBean = message.obj as CheckVersionBean?
                SharedPreferencesUtil.saveInfo(
                    CACHE_CHECK_UPDATE,
                    JsonHelper.parserObject2Json(checkVersionBean)
                )
                checkVersionBean?.let {
                    if (DeviceUtils.getVersionCode(this) < checkVersionBean.versionNo) {
                        showCheckVersionDialog(it)
                    }
                }
            }
            WHAT_REQUEST_PERMISSION_DISAGREE -> {
                finish()
            }
            WHAT_REQUEST_PERMISSION_AGREE -> {

            }
            WHAT_REQUEST_PERMISSION_ALWAYS_DISAGREE -> {
                XPopup.Builder(this).isDestroyOnDismiss(true).dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false).asConfirm("权限提示", "为了功能的正常使用,请打开存储、电话、通讯录权限哦", {
                        intentToSettingActivity()
                    }, {
                        finish()
                    }).show()
            }
            WHAT_POST_PHONE_RECORD_SUCCESS -> {
                // 如果通话记录文件存在，则上传
                if (record.fileUrl.isNotEmpty()) {
                    mPresenter.upload(Message.obtain(this, true), record.fileUrl, record.uid)
                }
            }
            WHAT_UPLOAD_FILE_SUCCESS -> {
                record.fileUrl = ""
                record.save()
            }
        }
    }

    override fun showMessage(message: String) {
        ArtUtils.snackbarText(message)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
        TimerUtils.getInstance().cancelAllTimes()
        DownLoadHelper.removeDownLoadCallBack()
    }

    @Subscriber(mode = ThreadMode.MAIN)
    fun onReceiveEvent(msg: EventMessage<Any>) {
        when (msg.code) {
            EVENT_BROADCAST_CALL_FINISH -> {
                record = msg.data as CachePhoneRecord
                if (phoneRingTime == record.phoneRingTime) {
                    LoggerUtils.d("重复数据提交：$record")
                    return
                }
                phoneRingTime = record.phoneRingTime
                LoggerUtils.d("广播返回的数据：$record")
                getPhoneRecord()
                (mFragments[0] as PhoneRecordFragment).loadRecordData()
                LoggerUtils.d("加工后完整的数据：$record")
                (mFragments[1] as PhoneCallFragment).clearPhoneNum()
                // 上传通话记录，创建一个列表并添加一条记录
                val paramsList = mutableListOf<PhoneRecordBean>()
                    .apply {
                        add(
                            PhoneRecordBean(
                                userName = record.userName,
                                phoneInNumber = record.userPhone,
                                phoneOutNumber = record.customerPhone,
                                phoneRingTime = record.phoneRingTime,
                                phoneStartTime = if (record.isConnect()) record.phoneStartTime else record.phoneEndTime,
                                phoneEndTime = record.phoneEndTime,
                                phoneCallType = record.phoneCallType,
                                phoneStatus = record.phoneStatus,
                                uid = record.uid,
                                customerPhone = record.customerPhone,
                                userPhone = record.userPhone,
                                phoneOperator = record.phoneOperator,
                                relegation = record.relegation,
                                phoneType = record.phoneType,
                                callDuration =  if (record.isConnect()) record.phoneDurationTime else 0,
                                ringDuration = (record.ringDurationTime / 1000).toInt()
                            )
                        )
                    }
                LoggerUtils.d("通话上传的数据：$paramsList")
                var info = SharedPreferencesUtil.getInfo(COMPANY_INFO)
                LoggerUtils.d("info ：$info")
                LoggerUtils.d("token2 ：${SharedPreferencesUtil.getInfo(TOKEN)}")
                var bean = parserJson2Object(info, CompanyInfoBean::class.java)
                LoggerUtils.d("token ：${bean.access_token}")
                mPresenter.postPhoneRecord(Message.obtain(this, PhoneRecordParams(paramsList)))
            }
            EVENT_TOKEN_EXPIRED -> {
                switchAccount()
            }
            CODE_PUSH_DATA -> {
                pushMsgBean = msg.data as PushMsgBean
                pushMsgBean?.let {
                    callPhone(it.customerPhone)
                }
            }
            EVENT_BROADCAST_ACTION_SIM_LOADED -> {
                //SIM卡加载
                (mFragments[1] as PhoneCallFragment).refreshView()
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mExitTime > 2000) { //
                // 如果两次按键时间间隔大于2000毫秒，则不退出
                ArtUtils.snackbarText(getString(R.string.press_again_to_exit_app))
                mExitTime = System.currentTimeMillis() // 更新mExitTime
            } else {
                AppManager.getAppManager().appExit()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //从设置界面回调，再次申请权限
        if (requestCode == INTENT_REQUEST_PERMISSION) {
            mPresenter.requestPermission(Message.obtain(this))
        }
    }

    /**获取手机号码所属公司名称*/
    fun getProviderCompanyName(): String {
        val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val type = telephonyManager.subscriberId
        return when {
            type.startsWith("46000") || type.startsWith("46002") -> "移动"
            type.startsWith("46001") -> "联通"
            type.startsWith("46003") -> "电信"
            else -> "未知"
        }
    }
}